package com.xgzit.xgzmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xgzit.common.dto.es.SkuEsModel;
import com.xgzit.common.utils.R;
import com.xgzit.xgzmall.search.config.XgzmallElasticSearchConfig;
import com.xgzit.xgzmall.search.constant.EsConstant;
import com.xgzit.xgzmall.search.feign.ProductFeignService;
import com.xgzit.xgzmall.search.service.MallSearchService;
import com.xgzit.xgzmall.search.vo.AttrResponseVo;
import com.xgzit.xgzmall.search.vo.SearchParamVo;
import com.xgzit.xgzmall.search.vo.SearchResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 搜索服务实现类
 *
 * @Author xgz
 * @Date 2021-04-27 18:30
 */
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    /**
     * 操作es必备
     */
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public SearchResultVo search(SearchParamVo param) {
        SearchResultVo result = null;
        // 动态构建 查询需要的DSL语句
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 执行检索请求
            // search 方法需要SearchRequest searchRequest, RequestOptions options
            SearchResponse response = client.search(searchRequest, XgzmallElasticSearchConfig.COMMON_OPTIONS);
            // 分析响应数据，封装成自己想要的
            result = buildSearchResult(response, param);
            log.info(result.toString());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("搜索出错", e);
        }
        return result;
    }

    /**
     * 封装响应数据
     *
     * @param response :
     * @param param
     * @return com.xgzit.xgzmall.search.vo.SearchResultVo
     */
    private SearchResultVo buildSearchResult(SearchResponse response, SearchParamVo param) {
        SearchResultVo result = new SearchResultVo();
        //1、所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (Objects.nonNull(hits.getHits()) && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                // 将json字符串转换为对象
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (Objects.nonNull(param.getKeyword()) && !StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                esModels.add(skuEsModel);
            }
        }
        result.setProducts(esModels);
        // 2、所涉及的属性信息  这个一个嵌入式的
        List<SearchResultVo.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attr_id_buckets = attr_id_agg.getBuckets();
        for (Terms.Bucket bucket : attr_id_buckets) {
            SearchResultVo.AttrVo attrVo = new SearchResultVo.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue();

            ParsedStringTerms aggr_name_agg = bucket.getAggregations().get("aggr_name_agg");
            String attrName = aggr_name_agg.getBuckets().get(0).getKeyAsString();

            ParsedStringTerms attr_value = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value.getBuckets().stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        // 3、所涉及的品牌信息
        List<SearchResultVo.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResultVo.BrandVo brandVo = new SearchResultVo.BrandVo();
            // 1、得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            // 2、得到品牌的名  在子聚合里面
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brand_name = brand_name_agg.getBuckets().get(0).getKeyAsString();
            // 3、得到品牌的图片 也在子聚合里面
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brand_img = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brand_name);
            brandVo.setBrandImg(brand_img);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
        // 4、所涉及的分类信息
        List<SearchResultVo.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResultVo.CatalogVo vo = new SearchResultVo.CatalogVo();
            String keyAsString = bucket.getKeyAsString();
            vo.setCatalogId(Long.parseLong(keyAsString));
            // 得到子聚合里面的信息
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            vo.setCatalogName(catalog_name);
            catalogVos.add(vo);
        }
        result.setCatalogs(catalogVos);
        // 5、分页信息 当前页码、总记录数、总页数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                (int) total / EsConstant.PRODUCT_PAGESIZE : (1 + (int) total / EsConstant.PRODUCT_PAGESIZE);
        result.setTotalPages(totalPages);
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        result.setPageNum(param.getPageNum());

        // 6、面包屑导航
        if (Objects.nonNull(param.getAttrs()) && !CollectionUtils.isEmpty(param.getAttrs())) {
            List<SearchResultVo.NavVo> navVos = param.getAttrs().stream().map(attr->{
                SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                // 记录筛选了的属性
                result.getAttrIds().add(Long.parseLong(s[0]));
                if (r.getCode() == 0){
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                }else {
                    navVo.setNavName(s[0]);
                }
                // 2、取消了面包屑，我们要跳转到哪个地方，将请求地址的url替换
                // 拿到当前所有的查询条件，去掉当前
                String replace = replaceQueryString(param, attr, "attrs");
                navVo.setLink("http://search.xgzmall.com/list.html?"+replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
        if (Objects.nonNull(param.getBrandId()) && !CollectionUtils.isEmpty(param.getBrandId())) {
            List<SearchResultVo.NavVo> navs = result.getNavs();
            SearchResultVo.NavVo navVo = new SearchResultVo.NavVo();
            navVo.setNavName("品牌");
            // todo 远程查询所有品牌
            R infos = productFeignService.brandInfos(param.getBrandId());
            if (infos.getCode() == 0) {
                List<SearchResultVo.BrandVo> brand = infos.getData("brand", new TypeReference<List<SearchResultVo.BrandVo>>() {
                });
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (SearchResultVo.BrandVo brandVo : brand) {
                    buffer.append(brandVo.getBrandName()).append(";");
                    replace = replaceQueryString(param, brandVo.getBrandId().toString(), "brandId");
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.xgzmall.com/list.html?"+replace);
            }
            navs.add(navVo);
        }
        // todo 分类导航 不需要导航取消
        return result;
    }
    /**
    * URL 替换
    * @param param:
    * @param value:
    * @return java.lang.String
    */
    private String replaceQueryString(SearchParamVo param, String value, String key) {
        String encode = "";
        try {
            // 浏览器对空格变成%20，而java是变成+号，特殊处理
            encode = URLEncoder.encode(value, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return param.get_queryString().replace("&"+ key +"=" + encode, "");
    }

    /**
     * 准备检索请求
     * 模糊匹配、过滤【属性、分类、品牌、价格区间、库存】 、排序、分页、高亮、聚合
     *
     * @param param:
     * @return org.elasticsearch.action.search.SearchRequest
     */
    private SearchRequest buildSearchRequest(SearchParamVo param) {
        String[] indices = new String[]{EsConstant.PRODUCT_INDEX};
        // SearchSourceBuilder 用来构建dsl语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /** 查询：、过滤【属性、分类、品牌、价格区间、库存】 */
        // QueryBuilders 是构建QueryBuilder的工具类
        // 1、构建boolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1、bool-must-模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("skuTitle", param.getKeyword());
            boolQuery.must(matchQuery);
        }
        // 1.2.1 bool-filter-term Catalog3Id
        if (Objects.nonNull(param.getCatalog3Id())) {
            TermQueryBuilder termQueryCatalogId = QueryBuilders.termQuery("catalogId", param.getCatalog3Id());
            boolQuery.filter(termQueryCatalogId);
        }
        // 1.2.2 bool-filter-terms brandId
        if (Objects.nonNull(param.getBrandId()) && (param.getBrandId().size() > 0)) {
            TermsQueryBuilder termsQueryBrandId = QueryBuilders.termsQuery("brandId", param.getBrandId());
            boolQuery.filter(termsQueryBrandId);
        }
        // todo 1.2.3 bool-filter- attrs.attrId 复杂
        if (Objects.nonNull(param.getAttrs()) && param.getAttrs().size() > 0) {

            for (String attr : param.getAttrs()) {
                BoolQueryBuilder nestBoolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个条件都 必须拼装成nested查询条件
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // 1.2.4 bool-filter-term hasStock
        if (Objects.nonNull(param.getHasStock())) {
            TermQueryBuilder termQueryHasStock = QueryBuilders.termQuery("hasStock", param.getHasStock() == 1);
            boolQuery.filter(termQueryHasStock);
        }
        // 1.2.5 bool-filter-range skuPrice
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            String[] s = param.getSkuPrice().split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                if (param.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        sourceBuilder.query(boolQuery);
        /** 排序、分页、高亮、聚合 */
        //2.1、排序 sort=hostScore_asc/desc
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }
        //2.2、分页 from = (pageNum - 1) * pageSize
        sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
        /** 聚合*/
        // 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg");
        brand_name_agg.field("brandName").size(1);
        TermsAggregationBuilder brand_img_agg = AggregationBuilders.terms("brand_img_agg");
        brand_img_agg.field("brandImg").size(1);
        brand_agg.subAggregation(brand_name_agg);
        brand_agg.subAggregation(brand_img_agg);

        sourceBuilder.aggregation(brand_agg);
        // 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(1);
        TermsAggregationBuilder catalog_name_agg = AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1);
        catalog_agg.subAggregation(catalog_name_agg);
        sourceBuilder.aggregation(catalog_agg);
        // 属性聚合 attr_agg
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 分析当前attr_id 对应的名字
        TermsAggregationBuilder aggr_name_agg = AggregationBuilders.terms("aggr_name_agg").field("attrs.attrName").size(1);
        // 分析当前attr_id 对应的所有可能的属性值 attrValue
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50);
        attr_id_agg.subAggregation(aggr_name_agg);
        attr_id_agg.subAggregation(attr_value_agg);
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);
        String s = sourceBuilder.toString();
        log.info(s);
        return new SearchRequest(indices, sourceBuilder);
    }
}
